<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/roles' }">权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
<!--      添加用户区-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
<!--      权限列表区-->
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand" >
          <template slot-scope="scope">
            <el-row
              :class="['bdBottom', index1 === 0 ? '' : 'bdTop' ,'vCenter']"
         
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id">
<!--              一级权限-->
              <el-col :span="5">
                <el-tag closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
<!--    二级权限-->
              <el-col :span="19">
                <el-row v-for="(item2, index2) in item1.children" :key="item2.id" :class="['vCenter', index2=== 0 ? '' : 'bdtop']">
                  <el-col :span="6">
                    <el-tag type="success" closable>{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightsById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" ></el-table-column>
        <el-table-column label="角色名称" prop="roleName" ></el-table-column>
        <el-table-column label="技术负责人" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size='mini' icon="el-icon-edit" type="primary" @click="editUser(scope.row.id)">编辑</el-button>
            <el-button size='mini' icon="el-icon-delete" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
            <el-button size='mini' icon="el-icon-setting" type="warning" @click="showRights(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
<!--      添加用户对话框-->
      <el-dialog
        title="提示"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="rightsDialogClosed"
        >
        <el-form :model="addUserForm"
                 label-width="100px"
                 :rules="addUserFormRules"
                 @close="addUserFormClosed"
                 ref="addUserFormRef">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addUserForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addUserForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
      </el-dialog>
<!--      修改用户对话框-->
      <el-dialog
        title="提示"
        :visible.sync="editDialogVisible"
        width="50%">
        <el-form :model="editForm" :rules="editFromRules" ref="editFormRef" label-width="100px" @close="editDialogClosed">
          <el-form-item label="角色名称" >
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="技术负责人" prop="mobile">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSubmit">确 定</el-button>
        </span>
      </el-dialog>
<!--      分配权限对话框-->
      <el-dialog
        title="分配权限"
        :visible.sync="showRightsDialogVisible"
        width="50%">
        <el-tree
          :data="rightsList"
          ref="treeRef"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="treeKeys"
          :props="treeProps">
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showRightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      //权限列表
      roleList: [],
      //添加用户对话框
      addDialogVisible: false,
      //用户列表数据
      addUserForm: {
        roleName: '',
        roleDesc: ''
      },
      //添加用户验证规则
      addUserFormRules: {
        roleName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入用户描述', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      //修改用户表单
      editForm: {
      
      },
      editFromRules: {
      
      },
      editDialogVisible: false,
      //修改的用户id
      editUserId: '',
      //分配权限
      showRightsDialogVisible: false,
      //权限列表数据
      rightsList: [],
      //属性结构连接
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      //默认选中的复选框的id的数组
      treeKeys: [],
      //用户id
      roleId: 0
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      let { data : res } = await this.$http.get(`roles`)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleList = res.data
      // console.log(this.roleList)
    },
    //添加用户
    async addUser () {
      // 发送请求
      let { data : res } = await this.$http.post(`roles`, this.addUserForm)
      this.addUserForm = res.data
      if (res.meta.status !== 201) return this.$message.error('添加用户失败')
      this.addDialogVisible = false
      this.getRolesList()
    },
    //表单关闭时
    addUserFormClosed() {
      this.$refs.addUserFormRef.resetFields()
    },
    //修改用户信息
    async editUser (id) {
      this.editUserId = id
      //根据id查询出用户信息
      let { data : res } = await this.$http.get(`roles/${id}`)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //点击确定完成用户修改功能
    async editSubmit () {
      let { data : res } = await this.$http.put('roles/' + this.editUserId, {
        roleName: this.editForm.roleName,
        roleDesc: this.editForm.roleDesc
      })
      if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
      this.editDialogVisible = false
      this.getRolesList()
    },
    //删除用户功能
    async deleteUser (id) {
      //先确认是否需要删除
      let result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      if (result !== 'confirm') return this.$message.info('您已取消删除')
      // eslint-disable-next-line no-unused-vars
      let{ data:res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.getRolesList()
    },
    //删除权限
    async removeRightsById(role, rightsId) {
      //先确认是否需要删除
      let result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      if (result !== 'confirm') return this.$message.info('您已取消删除')
      let { data : res } = await this.$http.delete(`roles/${role.id}/rights/${rightsId}`)
      //再重新赋值,让页面不在刷新
      role.children = res.data
    },
    //分配权限
    async showRights (role) {
      this.roleId = role.id
      //发送请求
      let{ data:res } = await this.$http.get(`rights/tree`)
      this.rightsList = res.data
      this.getKeys(role, this.treeKeys)
      this.showRightsDialogVisible = true
    },
    //获取keys的函数
    getKeys(node, arr) {
      //看是不是三级节点就看有没有children属性
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getKeys(item, arr)
      })
    },
    //关闭对话框,清空数组
    rightsDialogClosed() {
      this.treeKeys = []
    },
    //授权用户,
    async allotRights () {
      // 定义一个存放所有全选状态和半选状态的数组
      let keys = [
        ...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 将数组转化为字符串
      let idStr = keys.join(',')
      //发送请求
      let { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.showRightsDialogVisible = false
      this.getRolesList()
    }
  }
}
</script>

<style scoped lang="stylus">
  .el-tag
    margin 7px
  .bdTop
    border-top 1px solid #eee
  .bdBottom
    border-bottom: 1px solid #eee;
  .vCenter
    display flex;
    align-items center
  
</style>
